<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1200px" @open="open" @close="close">
    <!-- 是否为经营管理部初审 -->
    <el-form class="tl-form" ref="dealform" :model="model" :rules="rules" label-width="120px" v-if="extraParam==='CSApproval'">
      <br>
      <br>
      <el-row>
        <el-col :span="12">
          <el-form-item label="审批部门" prop="approvaldepartment">
            <el-select v-model="model.approvaldepartment" filterable collapse-tags clearable multiple>
              <el-option v-for="item in codeModel.approvalDepartmentList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="120px" :disabled="(disableEditSubmit || disableSave)&&(user.code!==model.modifyzhangqiusercode)">
      <el-collapse v-model="activeName">
        <el-collapse-item name="1" title="【合同】基本信息">
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目" prop="projectid" :required="true" :rules="rules.validateRequire">
                <el-input v-model="model.dispprojectid" :disabled="true" class="tl-ref-selector">
                  <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmProjectRefDialog" v-if="!disableEditSubmit && !disableSave"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同所属组织" prop="contractorgname" :required="true" :rules="rules.validateRequire">
                <tl-ref-org v-model="model.contractorgname" :initDisplayData.sync="model.contractorgname" dataType="code" :singleSelect="true" @confirm="onSelectOrg" :disabled="disableEditSubmit || disableSave"></tl-ref-org>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="12">
                    <el-form-item label="合同所属组织编码" prop="contractorgcode">
                        <el-input v-model="model.contractorgcode"></el-input>
                    </el-form-item>
                </el-col> -->
            <el-col :span="12">
              <el-form-item label="合同所属部门" prop="contractdeptname" :required="true" :rules="rules.validateRequire">
                <tl-ref-dept v-model="model.contractdeptname" :initDisplayData.sync="model.contractdeptname" dataType="code" nameType="fullname" :singleSelect="true" @confirm="onSelectDept" :disabled="disableEditSubmit || disableSave" :externalQueryParam="{qry_enabled:1}"></tl-ref-dept>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customername" :required="true" :rules="rules.validateRequire">
                <el-input v-model="model.customername" :disabled="true" class="tl-ref-selector">
                  <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmCustomerRefDialog" v-if="!disableEditSubmit && !disableSave"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
                 <el-col :span="12">
                    <el-form-item label="合同所属部门编码" prop="contractdeptcode">
                        <el-input v-model="model.contractdeptcode"></el-input>
                    </el-form-item>
                </el-col>
                 <el-col :span="12">
                    <el-form-item label="客户" prop="customerid">
                        <el-input v-model="model.customerid"></el-input>
                    </el-form-item>
                </el-col>
            </el-row> -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同名称" prop="contractname" :rules="rules.validateRequire">
                <el-input v-model="model.contractname" :disabled="disableEditSubmit || disableSave"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同日期" prop="contractdate" :rules="rules.validateRequire">
                <el-date-picker v-model="model.contractdate" type="date" placeholder="合同日期" value-format="yyyy-MM-dd" :disabled="disableEditSubmit || disableSave"></el-date-picker>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
                    <el-form-item label="合同编号" prop="contractcode">
                        <el-input v-model="model.contractcode" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="本次合同金额" prop="contractmoney" :rules="rules.validateRequire">
                <el-input-number v-model="model.contractmoney" controls-position="right" :step="1" :precision="2" style="width:95%" :disabled="disableEditSubmit || disableSave"></el-input-number>
                <span>元</span>
              </el-form-item>
            </el-col>
            <el-col :span="11" :offset="1">
              <el-alert title="提示：若本次合同金额为负值，则项目合同总金额会减去相应值。" type="warning" :closable="false">
              </el-alert>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="账期类型" prop="paytype" :rules="rules.validateRequire">
                <el-select v-model="model.paytype" filterable clearable :disabled="(disableEditSubmit || disableSave)&&(user.code!==model.modifyzhangqiusercode)">
                  <el-option v-for="item in codeModel.paytypeList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="账期方式" prop="paymethod" :rules="rules.validateRequire">
                <el-row>
                  <el-col :span="22">
                    <el-input v-model="model.paymethod" :disabled="true" class="tl-ref-selector">
                      <el-button slot="append" type="primary" icon="el-icon-search" @click="openTlErpAccountPeriodDialog" :disabled="payMethodEnble"></el-button>
                    </el-input>
                  </el-col>
                  <el-col :span="2">
                    <tl-help>
                      账期类型为“按客户账期”的话，账期方式、账期名称、ERP来源编码信息会自动填补；
                      账期类型为“按合同账期”的话，账期方式需要手动选择
                    </tl-help>
                  </el-col>
                </el-row>
                <!-- <erp-account-period v-model="model.paymethod" :initDisplayData.sync="model.paymethod" :singleSelect="true"></erp-account-period> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账期名称" prop="payname">
                <el-input v-model="model.payname" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="ERP来源编码" prop="erpsourcecode">
                <el-input v-model="model.erpsourcecode" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="机会点编号" prop="chancebackbonecode" :rules="model.ishistorycontract == '1' ? { required: false } : rules.validateRequire" class="tl-ref-selector">
                <el-input v-model="model.chancebackbonecode" :disabled="true" >
                  <el-button slot="append" icon="el-icon-search" @click="openRefChance"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机会点名称" prop="chancebackbonename" :rules="model.ishistorycontract == '1' ? { required: false } : rules.validateRequire" >
                <el-input v-model="model.chancebackbonename" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="description">
                <el-input v-model="model.description" type="textarea" :rows="2" :disabled="disableEditSubmit || disableSave"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item name="2" title="【合同】邮寄信息">
          <el-row>
            <el-col :span="12">
              <el-form-item label="收件人" prop="receiver" :rules="rules.validateRequire">
                <el-input v-model="model.receiver" :disabled="disableEditSubmit || disableSave"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收件人电话" prop="phone" :rules="rules.validateRequire">
                <el-input v-model="model.phone" :disabled="disableEditSubmit || disableSave"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="回寄地址" prop="postal" :rules="rules.validateRequire">
                <el-input v-model="model.postal" :disabled="disableEditSubmit || disableSave"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="快递单号" prop="couriernumber" v-show="model.state == '9' || model.couriernumber != null">
                <el-input v-model="model.couriernumber" :disabled="disableEditSubmit || disableSave"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="快递方式" prop="courier" v-show="model.state == '9' || model.courier != null">
                <el-select v-model="model.courier" filterable clearable :disabled="disableEditSubmit || disableSave">
                  <el-option v-for="item in codeModel.courierList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item name="3" title="【单据】相关信息">
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请部门" prop="deptname">
                <tl-ref-dept v-model="model.deptcode" :initDisplayData.sync="model.deptname" :disabled="true" dataType="code" nameType="fullname" :singleSelect="true" :externalQueryParam="{qry_enabled:1}"></tl-ref-dept>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请公司" prop="orgname">
                <el-input v-model="model.orgname" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请人" prop="username">
                <tl-ref-user v-model="model.username" :initDisplayData.sync="model.username" :disabled="true" dataType="code" :singleSelect="true"></tl-ref-user>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人工号" prop="usercode">
                <el-input v-model="model.usercode" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="单据日期" prop="docdate" :rules="rules.validateRequire">
                <el-date-picker v-model="model.docdate" type="date" placeholder="单据日期" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="提交时间" prop="submitdate">
                <el-date-picker v-model="model.submitdate" type="datetime" placeholder="提交时间" disabled></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="审批流程" prop="flowid">
                <el-input v-model="model.dispflowid" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="state">
                <el-input v-model="model.dispstate" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <tl-approval-history ref="history" sourceType="PmContract" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit" v-if="uiOperateState<=2">取消</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit||(user.code===model.modifyzhangqiusercode&&model.state===9)" :disabled="disableSave&&user.code!==model.modifyzhangqiusercode">
        <svg-icon icon-class="save" />保存
      </el-button>
      <tl-attachment ref="attachmentRef" sourceType="PmContract" :sourceId="model.id" btnTitle="合同文件" :disabled="disableAttachment" :previewMode="false" :editable="stateEdit"></tl-attachment>
      <tl-attachment ref="attachmentSignRef" sourceType="PmSignContract" :sourceId="model.id" btnTitle="合同扫描件" :disabled="disableAttachment" :previewMode="false" :editable="false"></tl-attachment>
      <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval">
        <svg-icon icon-class="send" />提交审批
      </el-button>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory">
        <svg-icon icon-class="list" />审批历史
      </el-button>
      <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableDelApproval" :disabled="disableDelApproval">
        <svg-icon icon-class="undo" />取消审批
      </el-button>
    </div>
    <tlpm-project-ref ref="pmProjectRef" @confirm="getpmProjectRefData" :isSingleSelect="true"></tlpm-project-ref>
    <tlpm-customer-ref ref="pmCustomerRef" @confirm="getpmCustomerRefData" :isSingleSelect="true"></tlpm-customer-ref>
    <tl-erp-account-period ref="tlErpAccountPeriod" v-on:erpAccountPeriodDataClear="erpAccountPeriodDataClear" @confirm="getErpAccountPeriodData"></tl-erp-account-period>
    <tl-chance-select :externalQueryParam="chanceParam" @confirm="afterSelectChance" ref="refChance"></tl-chance-select>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
import tlpmProjectRef from '@/views/ProjectManage/pmProject/refList.vue'
import tlpmCustomerRef from '@/views/ProjectManage/pmCustomer/refList.vue'
import tlErpAccountPeriod from '@/views/ProjectManage/pmCustomer/erpAccountPeriod.vue'
import tlHelp from '@/components/help/help'
import tlChanceSelect from './components/chanceSelect'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { tlpmProjectRef, tlpmCustomerRef, tlErpAccountPeriod, tlHelp, tlChanceSelect },
  data() {
    return {
      moduleTitle: '项目合同',
      urlPrefix: '/pm/contract/',
      activeName: ['1', '2', '3'],
      disableAttachmentButton: true,
      extraParam: '',
      payMethodEnble: true,
      url: {
        // 额外的url
      },
      // 机会点参照选择 默认查询参数
      chanceParam: {}
    }
  },
  props: {
    projectId: {
      type: [Number, String],
      default: function() {
        return ''
      }
    },
    editFlag: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    'model.paytype'(newType, oldType) {
      if (newType === '0' && typeof this.model.customername === 'undefined') {
        this.payMethodEnble = true
        this.$set(this.model, 'paytype', '')
        this.$tap.alert('账期类型为“按客户账期”，请先选择客户！', 'warning')
      } else if (newType === '0' && this.model.customername !== null) {
        if (this.model.customerentity.paymethod === null || this.model.customerentity.payname === null || this.model.customerentity.erpsourcecode === null) {
          this.$tap.alert('该客户没有账期相关信息，请前往客户档案进行填写！', 'warning')
        } else {
          this.$set(this.model, 'paymethod', this.model.customerentity.paymethod)
          this.$set(this.model, 'payname', this.model.customerentity.payname)
          this.$set(this.model, 'erpsourcecode', this.model.customerentity.erpsourcecode)
        }
      } else if (newType === '1') {
        this.payMethodEnble = false
        // 新增合同时，选择为"按合同账期"的话，清空垃圾数据
        if (this.isAdd) {
          this.$set(this.model, 'paymethod', '')
          this.$set(this.model, 'payname', '')
          this.$set(this.model, 'erpsourcecode', '')
        }
      }
    }
  },
  methods: {
    erpAccountPeriodDataClear() {
      this.$refs.tlErpAccountPeriod.visible = false
      this.$set(this.model, 'payname', '')
      this.$set(this.model, 'erpsourcecode', '')
      this.$set(this.model, 'paymethod', '')
    },
    getErpAccountPeriodData(selectionRow, selectKey, selectionValue) {
      // 账期名称
      this.$set(this.model, 'payname', selectionRow.payname)
      // 账期方式
      this.$set(this.model, 'paymethod', selectionRow.paymethod)
      // erp来源编码
      this.$set(this.model, 'erpsourcecode', selectionRow.erpsourcecode)
    },
    openTlErpAccountPeriodDialog() {
      this.$refs.tlErpAccountPeriod.visible = true
    },
    assignDefaultValue() {
      if (this.isAdd) {
        // if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
        //     this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
        // }
        // this.$set(this.model, 'orgcode', this.org.code)
        // this.$set(this.model, 'orgname', this.org.name)
        // this.$set(this.model, 'deptcode', this.dept.code)
        // this.$set(this.model, 'deptname', this.dept.fullname)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'docdate', new Date())
      }
    },
    afterDelApproval() {
      this.disableAttachmentButton = false
    },
    doApprovalDepart(resolve, reject) {
      const { approvaldepartment, deptcode, id } = this.model
      if (approvaldepartment !== null && approvaldepartment !== undefined) {
        const param = {
          approvaldepartment: approvaldepartment,
          deptcode: deptcode,
          CSApproval: 1,
          id: id
        }
        putAction(this.url.edit, param)
          .then(res => {
            if (res.success) {
              resolve()
            } else {
              this.$tap.alert(res.message, 'warning')
              reject()
            }
          })
          .catch(err => {
            this.$tap.alert('保存审批部门信息失败，请联系系统管理员', 'warning')
            reject()
          })
      } else {
        resolve()
      }
    },
    loaded() {
      if (this.isAdd === false && this.disableEditSubmit === true) {
        var params = {
          sourceType: 'PmContract',
          sourceId: this.model.id
        }
        this.disableAttachmentButton = false
        getAction('/cbo/attachment/calculateCount', params).then((res) => {
          if (res.success) {
            if (res.result === 0) {
              this.disableAttachmentButton = true
              this.$emit('refresh')
            }
          }
        })
      }
      // 页面加载完毕执行
      if (!this.isAdd && this.model.docno) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
      }
    },
    /** 执行新增提交 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      this.$set(this.model, 'billuid', this.uid)
      postAction(this.url.add, this.model)
        .then(res => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            this.queryData(res.result.id)
            this.disableAttachmentButton = false
            this.isAdd = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch(err => {
          this.saveLoading = false
        })
    },
    onSelectDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      this.$set(this.model, 'contractdeptname', selectedDept.fullname)
      this.$set(this.model, 'contractdeptcode', selectedDept.code)
    },
    onSelectOrg(selectedOrgs) {
      const selectedOrg = selectedOrgs[0]
      this.$set(this.model, 'contractorgname', selectedOrg.name)
      this.$set(this.model, 'contractorgcode', selectedOrg.code)
    },
    /** 打开项目参照 */
    openpmProjectRefDialog() {
      this.$refs.pmProjectRef.visible = true
    },
    /** 获取项目参数数据 */
    getpmProjectRefData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'projectid', selectionRow.id)
      this.$set(this.model, 'dispprojectid', selectionRow.name)
      this.$set(this.model, 'contractdeptname', selectionRow.ownerdeptname)
      this.$set(this.model, 'contractdeptcode', selectionRow.ownerdeptcode)
      this.$set(this.model, 'contractorgname', selectionRow.ownerorgname)
      this.$set(this.model, 'contractorgcode', selectionRow.ownerorgcode)
      this.$set(this.model, 'deptcode', selectionRow.ownerdeptcode)
      this.$set(this.model, 'deptname', selectionRow.ownerdeptname)
      this.$set(this.model, 'orgcode', selectionRow.ownerorgcode)
      this.$set(this.model, 'orgname', selectionRow.ownerorgname)
    },
    /** 打开客户名称参照 */
    openpmCustomerRefDialog() {
      this.$refs.pmCustomerRef.visible = true
    },
    /** 获取客户名称参数数据 */
    getpmCustomerRefData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'customerid', selectionRow.id)
      this.$set(this.model, 'customername', selectionRow.name)
      this.$set(this.model, 'customerentity', selectionRow)
      // 选择完一次客户后，有可能又修改所选择的客户，故清空垃圾数据
      this.$set(this.model, 'payname', '')
      this.$set(this.model, 'paymethod', '')
      this.$set(this.model, 'erpsourcecode', '')
    },
    /** 提交审批前*/
    beforeApproval() {
      if (this.$refs.attachmentRef.fileList.length === 0) {
        this.$tap.alert('请上传合同附件！', 'warning')
        this.submitLoading = false
        return false
      }
      return true
    },
    // 打开机会点选择界面
    openRefChance() {
      this.chanceParam = {}
      this.$refs['refChance'].visible = true
    },
    // 机会点参照赋值
    afterSelectChance(selectedRows, selectedKeys, selectedValues) {
      this.$set(this.model, 'chancebackbonecode', selectedRows.code)
      this.$set(this.model, 'chancebackbonename', selectedRows.projectname)
    },
    close() {
      this.$emit('cancel')
    }
    /** 提交审批 */
    // doSubmitApproval() {
    //     if (!this.url.submit) {
    //         this.$tap.alert('请设置审批地址!', 'warning')
    //         return
    //     }
    //     this.submitLoading = true
    //     this.$tap
    //         .confirm('确定提交审批吗？提交后，单据内容不可修改！')
    //         .then((_) => {
    //             if (!this.beforeApproval()) {
    //                 return
    //             }
    //             if (this.$refs.attachmentRef.fileCount === 0) {
    //                 this.$tap.alert('请上传合同附件！', 'warning')
    //                 return
    //             }
    //             putAction(this.url.submit, this.model).then((res) => {
    //                 if (res.success) {
    //                     this.$tap.message(res.message, 'success')
    //                     this.queryData(this.model.id)
    //                     this.afterApproval()
    //                 } else {
    //                     this.$tap.alert(res.message, 'warning')
    //                 }
    //                 this.submitLoading = false
    //             })
    //         })
    //         .catch((_) => {
    //             this.submitLoading = false
    //         })
    // }
  }
}
</script>

